/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.sesame.domain.Album;
import com.sesame.domain.Image;
import com.sesame.domain.User;
import com.sesame.service.AlbumService;
import com.sesame.service.UserService;
import com.sesame.toolkit.Encrypt;

/**
 * @author r6c
 * 
 */
public class UploadImageController extends SimpleFormController {

    private AlbumService albumService;
    private String imageBase;
    private Album album;
    private List<Album> albumList;
    private Integer albumId;
    private Integer userId;

    public void setAlbumService(AlbumService albumService) {
        this.albumService = albumService;
    }

    public void setImageBase(String imageBase) {
        this.imageBase = imageBase;
    }

    protected Map referenceData(HttpServletRequest request) throws Exception {
        Map referenceData = new HashMap();
        userId = (Integer) request.getSession().getAttribute("userId");
        albumId = ServletRequestUtils.getIntParameter(request, "albumId");
        albumList = albumService.listAllAlbum(userId);
        referenceData.put("albumId", albumId);
        referenceData.put("albumList", albumList);
        return referenceData;
    }

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        MultipartFile srcFile = null;
        File outFile = null;
        File outFileDir = null;
        String srcFileName = null;
        String outFileName = null;
        String fullOutFileName = null;
        BufferedImage bufferedImage = null;
        BufferedImage outImage = null;
        java.awt.Image tempImage = null;
        Map model = errors.getModel();
        int fileCount = ServletRequestUtils.getIntParameter(request,
                "fileCount");
        int width;
        int height;
        double ratio;
        int outW;
        int outH;
        int longSide;
        String subPath = null;
        boolean valid[] = new boolean[21];
        boolean flag = false;
        int count = 0;
        Date date = new Date();
        String month;
        String root;

        albumId = ServletRequestUtils.getIntParameter(request, "albumId");
        album = albumService.showAlbum(albumId);
        model.put("albumId", albumId);
        model.put("albumList", albumList);
        if (album == null) {
            model.put("error_uploadImage", "该相册不存在！");
            return new ModelAndView(getFormView(), model);
        }
        if (!album.getUserId().equals(userId)) {
            model.put("error_uploadImage", "没有权限上传到该相册！");
            return new ModelAndView(getFormView(), model);
        }
        if (!(request instanceof MultipartHttpServletRequest)) {
            model.put("error_uploadImage", "无上传文件！");
            return new ModelAndView(getFormView(), model);
        }
        outFileName = "" + userId + "_" + date.getTime();
        MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
        for (int i = 1; i <= fileCount; i++) {
            srcFile = multipart.getFile("file" + i);
            if (srcFile == null || srcFile.isEmpty()) {
                valid[i] = false;
                continue;
            }
            try {
                bufferedImage = ImageIO.read(srcFile.getInputStream());
                if (bufferedImage == null) {
                    valid[i] = false;
                    continue;
                }
                srcFileName = srcFile.getOriginalFilename();
                if (srcFileName.length() > 16) {
                    srcFileName = srcFileName.substring(0, 16);
                }
                width = bufferedImage.getWidth();
                height = bufferedImage.getHeight();
                ratio = (double) height / (double) width;
                if (date.getTime() % 100 < 10) {
                    root = "0" + date.getTime() % 100 + "/";
                } else {
                    root = date.getTime() % 100 + "/";
                }
                if (date.getMonth() < 9) {
                    month = "0" + (date.getMonth() + 1);
                } else {
                    month = "" + (date.getMonth() + 1);
                }

                subPath = root + (date.getYear() + 1900) + month + "/";
                outFileDir = new File(imageBase + subPath);
                if (!outFileDir.isDirectory()) {

                    outFileDir.mkdirs();
                }
                fullOutFileName = imageBase + subPath + outFileName + i;
                // 保存原图
                outFile = new File(fullOutFileName + "l.jpg");
                ImageIO.write(bufferedImage, "jpeg", outFile);
                // 保存中等图
                if (ratio < 0.75) {
                    if (width > 800) {
                        outW = 800;
                        outH = (int) (800 * ratio);
                    } else {
                        outW = width;
                        outH = height;
                    }
                } else {
                    if (height > 600) {
                        outW = (int) (600 / ratio);
                        outH = 600;
                    } else {
                        outW = width;
                        outH = height;
                    }
                }
                tempImage = bufferedImage.getScaledInstance(outW, outH,
                        java.awt.Image.SCALE_SMOOTH);
                outImage = new BufferedImage(outW, outH,
                        java.awt.Image.SCALE_SMOOTH);
                outImage.getGraphics().drawImage(tempImage, 0, 0, null);
                outFile = new File(fullOutFileName + "m.jpg");
                ImageIO.write(outImage, "jpeg", outFile);
                // 保存缩略图
                outImage = new BufferedImage(120, 120,
                        java.awt.Image.SCALE_SMOOTH);
                if (height > width) {
                    longSide = (int) (120 * ratio);
                    tempImage = bufferedImage.getScaledInstance(120, longSide,
                            java.awt.Image.SCALE_SMOOTH);
                    outImage.getGraphics().drawImage(tempImage, 0,
                            (120 - longSide) / 2, null);
                } else {
                    longSide = (int) (120 / ratio);
                    tempImage = bufferedImage.getScaledInstance(longSide, 120,
                            java.awt.Image.SCALE_SMOOTH);
                    outImage.getGraphics().drawImage(tempImage,
                            (120 - longSide) / 2, 0, null);
                }
                outFile = new File(fullOutFileName + "s.jpg");
                ImageIO.write(outImage, "jpeg", outFile);
            } catch (Exception e) {
            }
            // 写入数据库
            Image image = (Image) command;
            image.setUserId(userId);
            image.setCreateTime(date);
            image.setModTime(date);
            image.setTitle(srcFileName);
            image.setCollectAmount(0);
            image.setVisitAmount(0);
            image.setCommentAmount(0);
            image.setUrl(Encrypt.MapEncrypt(subPath + outFileName + i));
            image.setPrivacy(album.getPrivacy());
            albumService.newImage(image, model);
            flag = true;
            count++;
        }
        if (flag) {
            model.put("fileCount", fileCount);
            model.put("count", count);
            model.put("album", album);
            return new ModelAndView(getSuccessView(), model);
        } else {
            model.put("error_uploadImage", "没有合法的文件数据！");
            return new ModelAndView(getFormView(), model);
        }
    }
}